import _ from 'lodash';
import koa from 'koa';
import Router from '@koa/router';
import handle from '../handle';

import * as app from './app';
import * as boom from '@hapi/boom';
import * as jwt from '../utils/jwt';

import { auth } from '../middlewares/auth';
import { User } from './model';
import { validatePassword, validateUsername } from '../validate';

const router = new Router();

type RegisterBody = {
  username: string | null | undefined;
  password: string | null | undefined;
};

async function getCurrentUserInfo(ctx: koa.Context) {
  const user = (ctx as any).user as User;
  return user;
}

async function register(ctx: koa.Context) {
  const body = ctx.request.body as RegisterBody;
  const username = validateUsername(body.username);
  const password = validatePassword(body.password);
  await app.register(username, password);
  return { ok: true };
}

async function login(ctx: koa.Context) {
  const body = ctx.request.body as RegisterBody;
  const username = validateUsername(body.username);
  const password = validatePassword(body.password);

  if (await app.login(username, password)) {
    const user = await app.getUserByUsername(username);
    ctx.cookies.set('token', jwt.sign(user.id));
    return user;
  } else {
    throw boom.badRequest('用户名或者密码不正确');
  }
}

async function logout(ctx: koa.Context) {
  ctx.cookies.set('token'); // delete token
  return { ok: true };
}

async function getUserById(ctx: koa.Context) {
  const userId = +ctx.params.userId;
  if (!_.isInteger(userId)) {
    throw boom.badRequest('userId is not integer');
  }
  if (userId <= 0) {
    throw boom.badRequest('userId should be greater than 0');
  }

  return await app.getUserByUserId(userId);
}

router.post('/register', handle(register));
router.post('/login', handle(login));
router.post('/logout', auth, handle(logout));
router.get('/current', auth, handle(getCurrentUserInfo));
router.get('/:userId', handle(getUserById));

export default router;
